import React, { useLayoutEffect, useRef, useEffect, useState } from "react";
import { Modal, Button, Select, Input, Space, Image, message } from "antd";
import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";
import PickAssignmentModal from "./component/PickAssignmentModal";
import StockLockInModal from "./component/StockLockInModal";
import SafeValueModal from "./component/SafeValueModal";
import { FolderViewOutlined } from "@ant-design/icons";
import SelectActions from "@/views/components/SelectActions";
import WarehouseTransferModal from "./component/WarehouseTransferModal";
import PresentationRuleModal from "./component/PresentationRuleModal";
import { useNavigate } from "react-router-dom";
import { getCurrentUser } from "@/utils/authority";
import { getInventoryTotalList, getWarehouseList } from "./service";
import ActionExportExcelModal from "./component/ActionExportExcelModal"; // 导出弹窗
import useColumns from "./cloumns";
const GoodsStock = () => {
	const [visible, setVisible] = useState(0); //快销采购弹窗
	const navigate = useNavigate();
	const refWarehouseSort = useRef('desc');
	const defaultValue = useRef();

	// const [defaultValue, setDefaultValue] = useState("");
	const [selectedWarehouse, setSelectedWarehouse] = useState("");
	const [record, setRecord] = useState(null);
	const tableRequest = getInventoryTotalList;
	const [orderCreationTimeSort, setOrderCreationTimeSort] = useState();
	// const [warehouseList, setWarehouseList] = useRef([]);
	const warehouseList = useRef();
	const { defaultColumns } = useColumns({
		handleOpenStockLockVisible,
		handleJump,
		fetchPage,
		warehouseList,
		defaultValue,
		refWarehouseSort,
		setOrderCreationTimeSort,
		handleWarehouseChange,
		selectedWarehouse
	});
	const [columns, setColumns] = useState(defaultColumns);
	async function beforeQuerySearch({ API_DATA }) {
		console.log(warehouseList, "warehouseIdssssssssssssssssss");
		if (API_DATA.skuNum) {
			API_DATA["symbol"] = API_DATA.symbol !== undefined ? API_DATA.symbol : 1;
		}
		API_DATA["totalNumSort"] = refWarehouseSort?.current || 'desc';
		console.log(localStorage.getItem("sotckRule"), 'localStorage.getItem("sotckRule")');
		API_DATA["needHideZero"] =
			localStorage.getItem("sotckRule") !== "null" && localStorage.getItem("sotckRule") ? localStorage.getItem("sotckRule") : "1";
		return API_DATA;
	}
	useEffect(() => {
		getWarehouseFunc();
	}, []);
	async function getWarehouseFunc() {
		const { data = [], success } = await getWarehouseList({});
		if (success) {
			data.map(x => {
				(x.value = x.id), (x.label = x.warehouseName);
				return x;
			});
			fetchList({ warehouseId: data?.[0].id });
			warehouseList.current = data;
			// if (data.length > 0) {
			// 	const warehouseId = data?.filter(x => x.kind == 1 && x.isDefault == 0).id;
			// 	form.setFieldValue("warehouseId", data[0].id);
			// 	defaultValue.current = warehouseId;
			// }
			data.forEach((i, index) => {
				let dataColumns = {
					name: i.warehouseName,
					width: 250,
					code: i.id,
					render: (text, record) => (
						<span>
							{record.esInventoryVOList.map(g => {
								if (g.warehouseId === i.id) {
									return (
										<div>
											<div style={{ fontWeight: 700 }}>{g.saleableNum}</div>
											<div>
												{g.type == 1 && (
													<div>
														<span onClick={() => handleOpenStockLockVisible(record)} className="mr10 common-color2">
															销售锁定数：{g.lockedNum ? g.lockedNum : 0}
														</span>
														<span>退货在途数：{g.returnWayNum ? g.returnWayNum : 0}</span>
													</div>
												)}
											</div>
											<div>
												{(g.type == 2 || g.type == 3) && (
													<div>
														<span>退货在途数：{g.returnWayNum ? g.returnWayNum : 0}</span>
													</div>
												)}
											</div>
										</div>
									);
								}
							})}
						</span>
					)
				};

				// columns.forEach(i => {
				// 	if (i.name == "采购在途") {
				// 		const list = data?.map(x => {
				// 			x.label = x.warehouseName;
				// 			x.value = x.id;
				// 			return x;
				// 		});
				// 		i.search.group[0] = {
				// 			code: "warehouseId",
				// 			formItemProps: {
				// 				initialValue: list[0]?.id
				// 			},
				// 			content: () => (
				// 				<Select defaultValue={list[0]?.id} value={list[0]?.id} style={{ width: "100%" }} options={list}></Select>
				// 			),
				// 			span: 8
				// 		};
				// 	}
				// });
				columns.splice(7 + index, 0, dataColumns);
				console.log(columns, "columns");
				const filteredArray = columns.filter((item, index) => {
					return columns.findIndex(otherItem => otherItem.name === item.name) === index;
				});
				setColumns(filteredArray);
			});
		}
	}

	const tableKey = "GoodsStock231";
	const { selectedKeys, selectedRows, fetchList, dataSource, form, query, pagination, updateDataSource, searchSimpleTableProps } =
		useTableConfig({
			tableKey,
			rowKey: "skuId",
			columns,
			tableRequest,
			pageSize: 500,
			pageSizeOptions: [50, 100, 500, 1000, 5000],
			autoFetch: false,
			hasPagination: true,
			hasQuickSearch: true,
			beforeQuerySearch,
			resetSourceData: false,
			hasColsSetting: true,
			hasToggleSearchForm: true,
			columnResize: true
		});
	function fetchPage() {
		const DATA = form.getFieldValue();
		fetchList(DATA);
	}
	async function handleWarehouseChange(value) {
		setSelectedWarehouse(value);
	}
	async function handleOpenStockLockVisible(record) {
		setVisible("StockLock");
		setRecord(record);
	}
	async function handleJump(type, record) {
		if (type == "Warehouse") {
			navigate("/views/order/storage");
		} else {
			const { skuCode, warehouseId } = record;
			navigate("/views/stock/AccessRecords", { state: { warehouseId, goodsCode: skuCode } });
		}
	}
	const commonHandleClick = (status, record) => {
		if (selectedRows.length || record || status == "PresentationRule") {
			if (status == "warehouseTransfer" && selectedRows.length > 1) {
				return Modal.info({ centered: true, content: "请勾选单条数据进行修改" });
			}
			setVisible(status);
			setRecord(record);
		} else {
			message.warning({ centered: true, content: "请先勾选数据进行操作" });
		}
	};

	const exportExcel = () => {
		setVisible("ProgressModal");
	};
	const leftBtns = (
		<Space>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick("updateStock")}>
				手动校验修改库存
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick("safeValue")}>
				设置发货仓安全库存
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => commonHandleClick("warehouseTransfer")}>
				调仓
			</Button>
			<Button style={{ marginRight: "8px" }} onClick={() => handleJump("Warehouse")}>
				仓库管理
			</Button>
			<Button onClick={exportExcel} style={{ marginRight: "8px" }}>
				表格导出
			</Button>
		</Space>
	);
	const rightBtns = (
		<Space>
			<SelectActions type="text" onClick={() => commonHandleClick("PresentationRule")}>
				<FolderViewOutlined className="main-color" />
				展示规则
			</SelectActions>
		</Space>
	);
	const CheckGoodsStockProps = {
		visible,
		selectedRows,
		selectedKeys,
		fetchList,
		selectedWarehouse,
		record,
		handleOk() {},
		handleCancel() {
			setVisible(0);
		}
	};
	const searchData = form.getFieldsValue();
	const realProps = {
		createTaskData: {
			businessParam: JSON.stringify({
				skuCode: searchData.skuCode,
				skuName: searchData.skuName,
				skuNum: searchData.skuNum,
				skuSpec: searchData.skuSpec,
				spuCode: searchData.spuCode,
				symbol: searchData.symbol,
				warehouseId: searchData.warehouseId,
				uuid: getCurrentUser().uuid,
				current: pagination.current, // 当前页
				size: pagination.pageSize, // 每页的数量
				testBusinessKey: 1
			}),
			taskType: 4003
		},
		onCancel() {
			setVisible("");
		}
	};
	return (
		<>
			<SearchCheckboxTable key={tableKey} leftBtns={leftBtns} rightBtns={rightBtns} {...searchSimpleTableProps} />
			{visible == "updateStock" && <PickAssignmentModal {...CheckGoodsStockProps} />}
			{visible == "safeValue" && <SafeValueModal {...CheckGoodsStockProps} />}
			{visible == "warehouseTransfer" && <WarehouseTransferModal {...CheckGoodsStockProps} />}
			{visible == "PresentationRule" && <PresentationRuleModal {...CheckGoodsStockProps} />}
			{visible == "StockLock" && <StockLockInModal {...CheckGoodsStockProps} />}
			{visible == "ProgressModal" && <ActionExportExcelModal {...realProps} />}
		</>
	);
};

export default React.memo(GoodsStock, () => {
	return true;
});
